<template>
  <div class="handleProcess">
    <div class="pageTitle">{{title}}</div>
    <PageTitle>基本信息</PageTitle>
    <BaseInfo :pdata="pData" v-if="showFlag" ref="BaseInfo"/>
    <p-skeleton :loading="!showFlag" active />
    <PageTitle>工艺路线编排</PageTitle>
    <p-skeleton :loading="!showFlag" active />
    <DrawRoute :pdata="pData" v-if="showFlag" ref="DrawRoute"/>
    <!-- <div class="footer">
      <p-button class="handleBtn" style="margin-right: 20px;" @click="processHandleCancel">取消</p-button>
      <p-button :loading="loading" v-if="look !== '1'" class="handleBtn" @click="processHandleConfirm" type="primary">确认</p-button>
    </div> -->
  </div>
</template>
<script>
import PageTitle from "@/components/PageTitle";
import BaseInfo from "./baseInfo";
import DrawRoute from "./drawRoute";
import mesPeProcess from "@/api/mesPeProcess";
export default {
  name: "handleProcess",
  components: {
    PageTitle,
    BaseInfo,
    DrawRoute,
  },
  data() {
    return {
      showFlag: false,
      loading: false,
      pData: null,
    };
  },
  computed: {
    title(){
      let str = '新增产品工艺路线';
      if (this.handle === 'edit'){
        str = '修改产品工艺路线'
      }
      if (this.look === '1'){
        str = '查看产品工艺路线'
      }
      return str;
    },
    handle(){
      return this.$route.query.handle
    },
    look(){
      return this.$route.query.look
    }
  },
  created() {
    if ( this.handle === 'edit' ){
      mesPeProcess.getRouter({
        routerCode: this.$route.query.routerCode,
        version: this.$route.query.version,
      }).then( res =>{
        if ( res.code === 0 ){
          this.pData = res.data;
          console.log(this.pData)
          this.showFlag = true 
        }else {
          this.$message.error(res.msg);
        }
      });
    }else if( this.handle === 'addAndEdit' ){
      mesPeProcess.copyRouter({
        routerCode: this.$route.query.routerCode,
        version: this.$route.query.version,
      }).then( res =>{
        if ( res.code === 0 ){
          this.pData = res.data;
          console.log(this.pData)
          this.showFlag = true 
        }else {
          this.$message.error(res.msg);
        }
      });
    }else {
      this.showFlag = true
    }
  },
  methods: {
    processHandleCancel(){
      this.$router.push({
        path: this.$route.path,
      })
    },
    processHandleConfirm(){
      const that = this;
      // 基本信息校验
      const ruleForm = that.$refs.BaseInfo.$refs.ruleForm;
      ruleForm.validate(valid => {
        if (valid) {
          let params = {
            mesPeRouteStationDTOS: [],
          };
          // 校验画布 并获取正确顺序的节点
          const drawRoute = that.$refs.DrawRoute;
          const curSortPens = drawRoute.getSortNodeArr();
          if ( !curSortPens || curSortPens.length === 0 ){
            return;
          }
          // 保存前端数据
          console.log(drawRoute.canvas.data.pens);
          params.frontData = JSON.stringify(drawRoute.canvas.data.pens);
          // 工艺路线基本信息数据
          const baseInfoForm = that.$refs.BaseInfo.form;
          const {
            // 基本信息
            productCode, // 产品编码
            routeCode, // 工艺路线编码
            routeType, // 工艺路线类型
            productName,  // 产品名称
            routeName, // 工艺路线名称
            productSpec, // 产品描述
            routeDes, // 工艺路线描述
            version, // 工艺路线版本
            // 封面制作
            sendCom, 
            useCom,
            preparedBy,
            approvedBy,
            designFileCode,
          } = baseInfoForm;
          params.mcode = productCode;
          params.routerType = routeType;
          params.routerCode = routeCode;
          params.routerDesc = routeDes;
          params.routerName = routeName;
          params.version = version;
          // SOP封面制作
          params.sendCom = sendCom;
          params.useCom = useCom;
          params.preparedBy = preparedBy;
          params.approvedBy = approvedBy;
          params.designFileCode = designFileCode;

          // type=1 新建 type=2 修改
          params.type = this.handle === 'edit' ? 2 : 1;

          let topIndex = 1; // 一级工序顺序 从 1开始
          // 工站数据
          curSortPens.forEach( element =>{
            if ( element.data && element.data.key === 'process'){
              // 当前节点配置的一级工序数据
              const topSite = element.data.firstItem; 
              // 当前一级工序工时
              let topHourArr = [];
              element.data.configTree.forEach( elem =>{
                elem.children.forEach( el => {
                  topHourArr.push(el.siteAttr.workstationHour);
                })
              });
              let topHour = 0;
              if ( topHourArr.length > 0 ){
                topHour = topHourArr.reduce((total, num) => (total + num));
              }
              // 配置的二级工序以及工站
              element.data.configTree.forEach((elem, index) => {
                // 当前二级工序工时
                let twoHour = 0;
                const twoHourArr = elem.children.map( et => et.siteAttr.workstationHour);
                if ( twoHourArr.length > 0 ){
                  twoHour = twoHourArr.reduce((total, num) => (total + num)); 
                }
                // 配置的工站
                elem.children.forEach((el, inD) => {
                  const siteAttr = el.siteAttr;
                  let returnWorkstation = ['',''];
                  let returnWorkstationCodeArr = siteAttr.returnWorkstationCode.split('-');
                  if ( returnWorkstationCodeArr.length > 0 ){
                    returnWorkstation = returnWorkstationCodeArr;
                  }
                  let picturesData = el.sopData.picturesData;
                  if (Object.prototype.toString.call(el.sopData.picturesData) === "[object String]"){
                    picturesData = JSON.parse(picturesData);
                  }
                  params.mesPeRouteStationDTOS.push({
                    // 工站基本属性
                    topHour: topHour,
                    topOrder: topIndex,
                    topProcessName: siteAttr.topProcessName,
                    twoHour: twoHour,
                    twoOrder: index + 1,
                    twoProcessName: siteAttr.twoProcessName,
                    workAddressCode: siteAttr.workAddressCode,
                    workstationCode: siteAttr.workstationCode,
                    workstationHour: siteAttr.workstationHour,
                    workstationName: siteAttr.workstationName,
                    workstationOrder: inD + 1,
                    returnWorkstationCode: returnWorkstation[0],
                    returnWorkstationName: returnWorkstation[1],
                    collectionBarcode: siteAttr.collectionBarcode, // 是否采集条码 1 是 2 否
                    collectionType: siteAttr.collectionType, // 条码采集类型
                    // 技能
                    mesPeRouterSkillList: el.skillData,
                    // 资源
                    mesPeRouterResourceList: el.sourceData,
                    // 工站BOM
                    mesPeBomMaintenanceList: el.bomData,
                    // 线材清单
                    mesPeWireListingList: el.wirerodData,
                    // 组件清单
                    mesPeComponentListList: el.moduleData,
                    // 耗损系数
                    mesPeConsumeCoefficientList: el.consumeData,
                    // 程序
                    mesPeConsumeCoefficientList: el.gramData,
                    // SOP -----
                    // 图片
                    makePictures: picturesData.map( el => {
                      return {
                        pictureUrl: el.filePath,
                      }
                    }),
                    // 操作步骤
                    mesPeMattersNeedAttentions: el.sopData.stepData,
                  })
                });
              })
              topIndex++;
            }
          });
          console.log(params);
          that.loading = true;
          mesPeProcess.postMesPeProcessRoute(params).then( res => {
            if ( res.code === 0 ){
              this.$router.push({
                path: this.$route.path,
              })
            }else {
              this.$message.warning(res.msg)
            }
            that.loading = false;
          });
        }
      });
    },
  },
};
</script>
<style scoped lang='less'>
.handleProcess{
  .footer{
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 50px;
    margin-bottom: 50px;
  }
}
</style>